package main

import (
	"runtime"
	"time"
	"log"
	"os"
        "io/ioutil"
	"encoding/json"
	"strconv"
)

type Config struct {
	Mysql struct{
		Host string
		Username string
		Password string
		Dbname string
		Charset string
	}
}

var DockerId string

func main() {
	//获取docker_id
	DockerId = getDockerId()
	//使用上多核
	runtime.GOMAXPROCS(runtime.NumCPU())
	//工作
	//for {
	go DoTask()
	//}

	os.Getpid()
}

//获取docker_id
func getDockerId() (string) {
	//TODO
	return "1"
}

//数据库配置信息
func GetConfig() Config {
	config_json, _ := ioutil.ReadFile("db_config.json")
	var config Config
	json.Unmarshal([]byte(config_json), &config)
	return config
}

func DoTask() {
	//获取可调度数据
	taskList := getTaskList();
	for _, task := range taskList {
		//获取Uri
		uri := getAmqpUriString(task)
		//调用消费者
		c, err := NewConsumer(uri, task["exchange"], task["exchange_type"], task["queue"], task["route_key"], "simple-tag")
		lifetimes,_ := task["time_out"]
		lifetime,_ := strconv.Atoi(lifetimes)
		if err != nil {
			log.Fatalf("%s", err)
		}

		if lifetime > 0 {
			log.Printf("running for %s", lifetime)
			time.Sleep(lifetime)
		} else {
			log.Printf("running forever")
			select {}
		}

		log.Printf("shutting down")

		if err := c.Shutdown(); err != nil {
			log.Fatalf("error during shutdown: %s", err)
		}
	}
}

func getAmqpUriString (task  map[string]string) string {
	userName := task["user_name"]
	passWord := task["password"]
	hostUri := task["connect"]

	amqpString := "amqp://" + userName + ":" + passWord + "@" + hostUri + "/"
	return amqpString
}
